package com.wutongyu.mannyburger;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;
import java.util.Random;

import static android.content.Context.MODE_PRIVATE;

import com.wutongyu.mannyburger.AllOrderActivity;

public class UserProfileFragment extends Fragment {

    private static final String TAG = "UserProfileFragment";
    private static final String ARG_PHONE = "phone";
    private static final String PREF_NAME = "user_prefs";
    private static final String KEY_LOGGED_IN_PHONE = "logged_in_phone";
    
    // 可用的头像资源ID数组
    private static final int[] AVATAR_RESOURCES = {
//            R.drawable.avatar_1,
//            R.drawable.avatar_2,
//            R.drawable.avatar_3,
            // 添加新的自定义头像资源
            R.drawable.avatar_custom_1,
            R.drawable.avatar_custom_2,
            R.drawable.avatar_custom_3,
            R.drawable.avatar_custom_4
            // 如果你有更多头像，可以继续添加
    };
    
    // 随机用户名前缀数组
    private static final String[] USERNAME_PREFIXES = {
            "美食家", "汉堡控", "吃货", "品味者", "美味达人", "食神", "饕餮客"
    };
    
    private String phone;
    private ImageView imageViewAvatar;
    private TextView textViewUsername;
    private TextView textViewPhone;
    private TextView textViewAddress;
    private TextView textViewEditAddress;
    private RecyclerView recyclerViewOrders;
    private TextView textViewNoOrders;
    private Button buttonLogout;
    
    private UserDatabaseHelper userDbHelper;
    private OrderDatabaseHelper orderDbHelper;
    private UserOrderAdapter orderAdapter;
    
    // 静态工厂方法，用于创建带有参数的Fragment实例
    public static UserProfileFragment newInstance(String phone) {
        UserProfileFragment fragment = new UserProfileFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PHONE, phone);
        fragment.setArguments(args);
        return fragment;
    }
    
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            phone = getArguments().getString(ARG_PHONE);
        }
        
        userDbHelper = new UserDatabaseHelper(requireContext());
        orderDbHelper = new OrderDatabaseHelper(requireContext());
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_user_profile, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        
        // 初始化视图
        imageViewAvatar = view.findViewById(R.id.image_view_avatar);
        textViewUsername = view.findViewById(R.id.text_view_username);
        textViewPhone = view.findViewById(R.id.text_view_phone);
        textViewAddress = view.findViewById(R.id.text_view_address);
        textViewEditAddress = view.findViewById(R.id.text_view_edit_address);
        recyclerViewOrders = view.findViewById(R.id.recycler_view_orders);
        textViewNoOrders = view.findViewById(R.id.text_view_no_orders);
        buttonLogout = view.findViewById(R.id.button_logout);
        
        // 设置电话号码
        textViewPhone.setText(phone);
        
        // 设置订单列表
        recyclerViewOrders.setLayoutManager(new LinearLayoutManager(getContext()));
        
        // 加载用户信息
        loadUserInfo();
        
        // 加载订单历史
        loadOrderHistory();
        
        // 设置地址编辑点击事件
        textViewEditAddress.setOnClickListener(v -> showEditAddressDialog());
        
        // 设置退出登录按钮点击事件
        buttonLogout.setOnClickListener(v -> logout());
        
        // 设置头像和用户名区域点击事件，跳转到个人信息页面
        View profileHeaderView = view.findViewById(R.id.layout_profile_header);
        if (profileHeaderView != null) {
            profileHeaderView.setOnClickListener(v -> navigateToUserInfo());
        } else {
            // 如果没有专门的容器，单独设置头像和用户名的点击事件
            imageViewAvatar.setOnClickListener(v -> navigateToUserInfo());
            textViewUsername.setOnClickListener(v -> navigateToUserInfo());
        }
    }
    
    private void loadUserInfo() {
        ContentValues userInfo = userDbHelper.getUserInfo(phone);
        
        if (userInfo != null) {
            // 处理用户名
            String username = userInfo.getAsString(UserDatabaseHelper.COLUMN_USERNAME);
            if (TextUtils.isEmpty(username)) {
                // 如果用户名为空，生成随机用户名
                username = generateRandomUsername();
                // 保存到数据库
                updateUserProfile(username, "", getRandomAvatarId());
            }
            textViewUsername.setText(username);
            
            // 处理地址
            String address = userInfo.getAsString(UserDatabaseHelper.COLUMN_ADDRESS);
            if (!TextUtils.isEmpty(address)) {
                textViewAddress.setText(address);
            }
            
            // 处理头像
            Integer avatarId = userInfo.getAsInteger(UserDatabaseHelper.COLUMN_AVATAR_ID);
            try {
                // 直接使用数据库中存储的资源ID，不进行额外映射
                if (avatarId != null && avatarId > 0 && isResourceValid(avatarId)) {
                    imageViewAvatar.setImageResource(avatarId);
                    imageViewAvatar.setBackgroundResource(0); // 移除背景
                    Log.i(TAG, "正在使用头像资源ID: " + avatarId);
                } else {
                    // 如果头像ID无效，使用安全的默认头像
                    int safeAvatarId = getSafeDefaultAvatarId();
                    imageViewAvatar.setImageResource(safeAvatarId);
                    imageViewAvatar.setBackgroundResource(0); // 移除背景
                    // 保存头像ID到数据库
                    updateUserAvatarId(safeAvatarId);
                    Log.w(TAG, "用户头像ID无效或不存在，已设置安全默认头像: " + safeAvatarId);
                }
            } catch (Exception e) {
                // 如果设置头像过程中出现任何问题，使用备用头像
                Log.e(TAG, "设置用户头像时出错: " + e.getMessage(), e);
                try {
                    // 尝试使用备用系统头像
                    imageViewAvatar.setImageResource(android.R.drawable.ic_menu_gallery);
                } catch (Exception fallbackEx) {
                    // 严重错误，无法设置任何头像，但不应导致应用崩溃
                    Log.e(TAG, "设置备用头像也失败，忽略头像显示", fallbackEx);
                }
            }
        } else {
            Log.e(TAG, "无法获取用户信息: " + phone);
            Toast.makeText(getContext(), "加载用户信息失败", Toast.LENGTH_SHORT).show();
        }
    }
    
    private void loadOrderHistory() {
        List<Order> userOrders = orderDbHelper.getOrdersByUserPhone(phone);
        
        if (userOrders != null && !userOrders.isEmpty()) {
            // 限制只显示最新的3个订单
            List<Order> recentOrders = userOrders;
            if (userOrders.size() > 3) {
                recentOrders = userOrders.subList(0, 3);
            }
            
            orderAdapter = new UserOrderAdapter(recentOrders);
            recyclerViewOrders.setAdapter(orderAdapter);
            
            // 添加点击事件，点击订单将跳转到所有订单页面
            orderAdapter.setOnItemClickListener(order -> {
                navigateToAllOrders();
            });
            
            // 添加"查看全部"文本并设置点击事件
            View viewAllOrdersView = getLayoutInflater().inflate(R.layout.item_view_all_orders, recyclerViewOrders, false);
            viewAllOrdersView.setOnClickListener(v -> navigateToAllOrders());
            
            // 将"查看全部"添加到RecyclerView下方
            ViewGroup ordersContainer = (ViewGroup) recyclerViewOrders.getParent();
            
            // 检查之前是否已经添加了"查看全部"按钮，避免重复添加
            for (int i = 0; i < ordersContainer.getChildCount(); i++) {
                View child = ordersContainer.getChildAt(i);
                if (child.getId() == R.id.text_view_view_all_orders) {
                    ordersContainer.removeView(child);
                    break;
                }
            }
            
            ordersContainer.addView(viewAllOrdersView);
            
            textViewNoOrders.setVisibility(View.GONE);
            recyclerViewOrders.setVisibility(View.VISIBLE);
        } else {
            textViewNoOrders.setVisibility(View.VISIBLE);
            recyclerViewOrders.setVisibility(View.GONE);
        }
    }
    
    private void showEditAddressDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_edit_address, null);
        builder.setView(dialogView);
        
        EditText editTextAddress = dialogView.findViewById(R.id.edit_text_address);
        Button buttonCancel = dialogView.findViewById(R.id.button_cancel);
        Button buttonSave = dialogView.findViewById(R.id.button_save);
        
        // 设置当前地址
        String currentAddress = textViewAddress.getText().toString();
        if (!currentAddress.equals("暂无地址，请点击编辑添加")) {
            editTextAddress.setText(currentAddress);
        }
        
        AlertDialog dialog = builder.create();
        
        buttonCancel.setOnClickListener(v -> dialog.dismiss());
        
        buttonSave.setOnClickListener(v -> {
            String newAddress = editTextAddress.getText().toString().trim();
            if (TextUtils.isEmpty(newAddress)) {
                editTextAddress.setError("地址不能为空");
                return;
            }
            
            // 更新地址
            boolean success = userDbHelper.updateUserAddress(phone, newAddress);
            if (success) {
                textViewAddress.setText(newAddress);
                Toast.makeText(getContext(), "地址已更新", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getContext(), "地址更新失败", Toast.LENGTH_SHORT).show();
            }
            
            dialog.dismiss();
        });
        
        dialog.show();
    }
    
    private void logout() {
        // 清除登录状态
        clearLoginState();
        
        // 返回到登录界面
        navigateToLogin();
    }
    
    private void clearLoginState() {
        SharedPreferences prefs = requireActivity().getSharedPreferences(PREF_NAME, MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.remove(KEY_LOGGED_IN_PHONE);
        editor.apply();
        Log.d(TAG, "已清除登录状态");
    }
    
    private void navigateToLogin() {
        if (!isAdded() || getActivity() == null || getActivity().isFinishing()) {
            Log.w(TAG, "Fragment未添加或Activity已销毁，取消导航");
            return;
        }
        
        // 返回到登录界面
        FragmentManager fragmentManager = getParentFragmentManager();
        if (fragmentManager.isStateSaved()) {
            Log.w(TAG, "FragmentManager状态已保存，取消导航");
            return;
        }
        
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.nav_host_fragment_container, new LoginFragment());
        transaction.commitAllowingStateLoss();
    }
    
    private String generateRandomUsername() {
        Random random = new Random();
        String prefix = USERNAME_PREFIXES[random.nextInt(USERNAME_PREFIXES.length)];
        int suffix = random.nextInt(1000);
        return prefix + suffix;
    }
    
    private int getRandomAvatarId() {
        try {
            Random random = new Random();
            // 直接返回随机头像资源ID
            int[] avatarResources = {
                R.drawable.avatar_custom_1,
                R.drawable.avatar_custom_2,
                R.drawable.avatar_custom_3,
                R.drawable.avatar_custom_4
            };
            return avatarResources[random.nextInt(avatarResources.length)];
        } catch (Exception e) {
            Log.e(TAG, "获取随机头像时出错", e);
            return R.drawable.avatar_custom_1; // 默认返回第一个头像
        }
    }
    
    private void updateUserProfile(String username, String address, int avatarId) {
        userDbHelper.updateUserInfo(phone, username, address, avatarId);
    }
    
    private void updateUserAvatarId(int avatarId) {
        ContentValues values = new ContentValues();
        values.put(UserDatabaseHelper.COLUMN_AVATAR_ID, avatarId);
        
        // 获取当前用户信息
        ContentValues userInfo = userDbHelper.getUserInfo(phone);
        String username = "";
        String address = "";
        
        if (userInfo != null) {
            username = userInfo.getAsString(UserDatabaseHelper.COLUMN_USERNAME);
            if (username == null) username = generateRandomUsername();
            
            address = userInfo.getAsString(UserDatabaseHelper.COLUMN_ADDRESS);
            if (address == null) address = "";
        }
        
        userDbHelper.updateUserInfo(phone, username, address, avatarId);
    }
    
    /**
     * 跳转到用户信息详情页面
     */
    private void navigateToUserInfo() {
        if (!isAdded() || getActivity() == null || getActivity().isFinishing()) {
            Log.w(TAG, "Fragment未添加或Activity已销毁，取消导航");
            return;
        }
        
        UserInfoFragment userInfoFragment = UserInfoFragment.newInstance(phone);
        FragmentManager fragmentManager = getParentFragmentManager();
        if (fragmentManager.isStateSaved()) {
            Log.w(TAG, "FragmentManager状态已保存，取消导航");
            return;
        }
        
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.nav_host_fragment_container, userInfoFragment);
        transaction.addToBackStack(null);
        transaction.commitAllowingStateLoss();
    }
    
    // 跳转到所有订单页面
    private void navigateToAllOrders() {
        try {
            Intent intent = new Intent(getActivity(), AllOrderActivity.class);
            startActivity(intent);
        } catch (Exception e) {
            Log.e(TAG, "跳转到所有订单页面失败: " + e.getMessage(), e);
            Toast.makeText(getContext(), "无法打开历史订单", Toast.LENGTH_SHORT).show();
        }
    }
    
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        // 关闭数据库连接
        if (userDbHelper != null) {
            userDbHelper.close();
        }
        if (orderDbHelper != null) {
            orderDbHelper.close();
        }
    }
    
    /**
     * 检查资源ID是否有效
     */
    private boolean isResourceValid(int resourceId) {
        try {
            if (getResources() == null) {
                Log.w(TAG, "资源检查时资源对象为空");
                return false;
            }
            
            // 尝试获取资源名称，如果资源不存在会抛出异常
            getResources().getResourceName(resourceId);
            
            // 进一步确认是否为可绘制资源
            try {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    getResources().getDrawable(resourceId, requireContext().getTheme());
                } else {
                    getResources().getDrawable(resourceId);
                }
                return true;
            } catch (Exception e) {
                Log.w(TAG, "资源ID " + resourceId + " 不是可绘制资源", e);
                return false;
            }
        } catch (Exception e) {
            Log.w(TAG, "资源ID无效: " + resourceId, e);
            return false;
        }
    }
    
    /**
     * 获取安全的默认头像ID
     */
    private int getSafeDefaultAvatarId() {
        // 自定义头像列表，按优先顺序排列
        int[] safeAvatars = {
            R.drawable.avatar_custom_1,
            R.drawable.avatar_custom_2,
            R.drawable.avatar_custom_3,
            R.drawable.avatar_custom_4
        };
        
        // 逐个尝试找到一个有效的头像资源
        for (int avatarId : safeAvatars) {
            if (isResourceValid(avatarId)) {
                return avatarId;
            }
        }
        
        // 如果所有自定义头像都无效，才使用系统图标作为最后备选
        try {
            return android.R.drawable.ic_menu_gallery;
        } catch (Exception e) {
            Log.e(TAG, "无法获取任何有效的头像资源", e);
            return 0; // 最终失败情况下返回0
        }
    }
} 